package com.qire.manhua.view.comicReader;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Rect;
import android.util.AttributeSet;

import com.qire.common.collect.SafeIterableList;
import com.qire.common.collect.SafeIterableList.Node;
import com.qire.common.collect.SafeIterableMap;
import com.qire.common.utils.EquipmentInfoUtil;
import com.qire.manhua.model.entity.BulletScreenInfo;
import com.qire.manhua.view.comicReader.renderer.BulletScreen;
import com.qire.manhua.view.comicReader.renderer.PictureResource;

import java.util.Iterator;

/**
 * 漫画阅读器：继承自图片阅读器 <br />
 * 扩展弹幕绘制功能弹幕相关操作。并默认切换至线程调度绘制模式。
 */
public class ComicReaderView extends PictureReaderView {

    /** 弹幕渲染器  */
    private final BulletScreenRenderer bulletScreenRenderer = new BulletScreenRenderer();

    /** 弹幕启用状态，true 表示启用打开， false 表示禁用关闭 */
    private boolean bulletScreenEnable = true;



    /** 当前阅读资源定位器，定位当前阅读到的资源及位置相关 */
    private ResourceLocator resourceLocator;

    public ComicReaderView(Context context) {
        this(context, null);
    }

    public ComicReaderView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ComicReaderView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        enableDrawScheduler();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //使用屏幕高度作为控件的高度
//        int heightMode      = MeasureSpec.getMode(heightMeasureSpec);
//        int screenHeight    = EquipmentInfoUtil.getScreenHeight();
//        heightMeasureSpec   = MeasureSpec.makeMeasureSpec(screenHeight, heightMode);

        int widthMode       = MeasureSpec.getMode(widthMeasureSpec);
        int screenWidth     = EquipmentInfoUtil.getScreenWidth();
        widthMeasureSpec    = MeasureSpec.makeMeasureSpec(screenWidth, widthMode);

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDrawVisible(Canvas canvas, int scrollX, int scrollY, PictureResource[] visibleResources) {
        super.onDrawVisible(canvas, scrollX, scrollY, visibleResources);

        if(bulletScreenEnable) {
            bulletScreenRenderer.scrollTo(scrollX, scrollY);

            Rect screenArea = new Rect(0, 0, getWidth(), getHeight());
            screenArea.offset(-scrollX, -scrollY);

            bulletScreenRenderer.draw(canvas, screenArea, visibleResources);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        bulletScreenRenderer.release();

        super.onDetachedFromWindow();
    }

    public void loadBulletScreen(SafeIterableMap<String, SafeIterableList<BulletScreenInfo>> bulletScreenInfoMap) {
        forEachResource((PictureResource resource) -> {
            SafeIterableList<BulletScreenInfo> bulletScreenInfoList = bulletScreenInfoMap.getValue(resource.token);
            if(bulletScreenInfoList == null)
                return;
            Iterator<Node<BulletScreenInfo>> iterator = bulletScreenInfoList.iteratorWithAdditions();
            while(iterator.hasNext()) {
                BulletScreenInfo info = iterator.next().value();
                bulletScreenRenderer.loadBulletScreen(resource.token, info.toBulletScreen(resource));
            }
        });
    }

    public void addBulletScreen(String key, BulletScreen bulletScreen) {
        bulletScreenRenderer.loadBulletScreen(key, bulletScreen);
    }

    public void pauseBulletScreen() {
        bulletScreenRenderer.pause();
    }

    public void goPlayBulletScreen() {
        bulletScreenRenderer.goPlay();
    }

    public void setIsOpenBulletScreen(boolean isOpenBulletScreen) {
        this.bulletScreenEnable = isOpenBulletScreen;
    }

    public void locateBulletScreen(BulletScreenInfo bulletScreenInfo) {
        // 获取当前 View 的可见区域，由于连续下滑模式存在所以当前的 View 可能只显示部分，所以需要获取可见区域
        Rect visibleRect = new Rect();
        getLocalVisibleRect(visibleRect);

        // 通过可见区域获取 View 可见部分的中心点。
        PointF visibleCenterPoint = new PointF(visibleRect.centerX(), visibleRect.centerY());

        // 获取当前滚动位置
        Point point = getScroll();

        // 计算可见区中心点位于完整漫画的坐标点。
        int x = (int) (visibleCenterPoint.x - point.x);
        int y = (int) (visibleCenterPoint.y - point.y);

        // 通过坐标位置找到所属漫画资源
        PictureResource resource = findResourceBy(x, y);
        if(resource != null) {
            Rect r = resource.calcViewportRect();
            int offsetX = x - r.left;
            int offsetY = y - r.top;
            bulletScreenInfo.loadPictureResource(resource, new Point(offsetX, offsetY));
        }
    }

    @Override
    protected void onLocateResources(PictureResource pictureResource, int comicHeight) {
        if(resourceLocator != null) {
            resourceLocator.onLocateResources(pictureResource, comicHeight);
        }
    }

    public void setResourceLocator(ResourceLocator resourceLocator) {
        this.resourceLocator = resourceLocator;
    }

    /**
     * 资源定位器，用于定位当前阅读到的资源
     */
    public interface ResourceLocator {
        /**
         * 滑动阅读到新资源位置时触发
         * @param pictureResource 当前阅读页右上角所处漫画图片资源
         * @param comicHeight 漫画整体高度
         */
        void onLocateResources(PictureResource pictureResource, int comicHeight);
    }

}
